﻿using SimDev.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SimDev.Config
{


    [Serializable]
    public class RegSimConfig
    {
        [XmlAttribute]
        public bool ValueIsRandom { get; set; }
        [XmlAttribute]
        public ushort FixValue { get; set; }
        [XmlAttribute]
        public ushort Maximum { get; set; }
        [XmlAttribute]
        public ushort Minimum { get; set; }
    }

    [Serializable]
    public class Register
    {
        [XmlAttribute]
        public string ReadName { get; set; }

        [XmlAttribute]
        public string WriteName { get; set; }

        [XmlAttribute]
        public int ReadAddress { get; set; }

        [XmlAttribute]
        public int WriteAddress { get; set; }

        [XmlAttribute]
        public string Type { get; set; }

        [XmlAttribute]
        public string DisplayFormat { get; set; }

        [XmlElement]
        public RegSimConfig RegSimConfig { get; set; }
    }
    [Serializable]
    public class RTUConfig
    {

        [XmlAttribute]
        public int Address { get; set; }

        //[XmlAttribute]
        //public string TypeName { get; set; }

        [XmlAttribute]
        public string Model { get; set; }


        [XmlArrayItem("Register")]
        public  List<Register> Registers { get; set; }
 

    }

    [Serializable]
    public class DTUConfig
    {
        [XmlAttribute]
        public string IMEI { get; set; }

        [XmlArrayItem("RTU")]
        public List<RTUConfig> RTUs { get; set; }
    }

    [Serializable]
    public class DevConfig
    {

        [XmlArrayItem("DTU")]
        public List<DTUConfig> DTUs { get; set; }

        [XmlAttribute]
        public string ServerIP { get; set; }

        [XmlAttribute]
        public int Port { get; set; }



        private const string SAVE_PATH = "Dev.Config";



        public static DevConfig Load()
        {
            if (!File.Exists(SAVE_PATH))
            {
                var config = new DevConfig();
                config.DTUs = new List<DTUConfig>();
                config.Save();
                return config;
            }

            return File.ReadAllText(SAVE_PATH, Encoding.UTF8).XmlDeserialize<DevConfig>();
        }

        public void Save()
        {
            File.WriteAllText(SAVE_PATH, this.XmlSerialize(), Encoding.UTF8);
        }

    }
}
